package com.csx.micrometer.invoke.context;

import org.springframework.util.LinkedCaseInsensitiveMap;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cuisongxu
 * @date 2022/12/3 17:11
 */
public abstract class MicrometerRequest implements MicrometerMessage {

    /**
     * 原始请求对象
     */
    protected final Object originRequest;
    /**
     * 请求对象属性缓存
     */
    protected Map<String, Object> attributeCache = new HashMap<>();
    /**
     * 请求头
     */
    protected Map<String, String> headers = new LinkedCaseInsensitiveMap<>();

    public MicrometerRequest(Object originRequest) {
        this.originRequest = originRequest;
    }

    public Object getOriginRequest() {
        return this.originRequest;
    }

    @Override
    public Object getAttribute(String key) {
        return attributeCache.get(key);
    }

    @Override
    public MicrometerMessage setAttribute(String key, Object value) {
        attributeCache.put(key, value);
        return this;
    }

    @Override
    public void removeAttribute(String key) {
        this.attributeCache.remove(key);
    }

    @Override
    public Map<String, Object> getAttributes() {
        return attributeCache;
    }

    @Override
    public String getHeader(String name) {
        return headers.get(name);
    }

    @Override
    public void setHeader(String name, String value) {
        headers.put(name, value);
    }

    @Override
    public <T> T getOriginMessage(Class<T> desiredType) {
        if(desiredType == null) {
            return null;
        }
        Object originRequest = getOriginRequest();
        if(desiredType.isInstance(originRequest)) {
            return desiredType.cast(originRequest);
        }
        return null;
    }

    // TODO 探究为什么IDEA推荐使用字符串拼接而非 StringBuilder的方式进行拼接
    @Override
    public String toString() {
        return "MicrometerRequest { originalRequest = " +
                originRequest +
                ", headers = " +
                getSingleValueHeaders() +
                ", attribute = " +
                getAttributes() +
                " }";
    }

    /**
     * 获取请求URL
     * @return
     */
   public abstract String getRequestURL();

    /**
     * 获取请求的资源
     * @return
     */
   public abstract String getRequestURI();

    /**
     * 获取请求方法
     * @return
     */
   public abstract String getMethod();

}
